package com.wskj.listen;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.wskj.common.core.domain.entity.SysUser;
import com.wskj.system.service.ISysUserService;
import com.wskj.workbench.enums.OrderRedisKeyEnum;
import com.wskj.workbench.service.ITbRedisKeyService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

import java.util.*;

/**
* Filename: RedisKeyExpirationListener.java
* Description: 监听失效KEY处理相关业务
* Copyright: Copyright (c) 2016-2019 All Rights Reserved. 
* Company: wsdz.com Inc. 
*
* @author: gunk
* @version: 1.0 
* Create at: 2022/8/22 17:22 
*
* Modification History: 
* Date Author Version Description 
* ------------------------------------------------------------------ 
* 2022/8/22 guqk 1.0 1.0 Version 
*/
@Component
@Slf4j
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {

    @Autowired
    private ITbRedisKeyService iTzRedisKeyService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private ISysUserService iSysUserService;

    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    @Override
    public void onMessage(Message message, byte[] pattern) {
        super.onMessage(message, pattern);
        // 由于通知收到的是redis key，value已经过期，无法收到，所以需要在key上标记业务数据。
        // 获取到失效的 key，进行取消订单业务处理
        String expiredKey = message.toString();
        // 注意：只能获取失效的key值，不能获取key对应的value值
        // 超时未付款,自动取消订单
        if(expiredKey.contains(OrderRedisKeyEnum.VIP_DUE_CANCEL.getValue())){
            // 修改用户已领取店铺优惠券状态为已过期
            log.info("redis定时任务，购买会员卡到期取消会员资格开始");
            String[] expiredKeys = expiredKey.split("-");
            Long userId = Long.parseLong(expiredKeys[1]);
            LambdaUpdateWrapper<SysUser> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            lambdaUpdateWrapper.eq(SysUser::getUserId,userId);
            lambdaUpdateWrapper.set(SysUser::getVipStatus,0);
            lambdaUpdateWrapper.set(SysUser::getDueDate,null);
            lambdaUpdateWrapper.set(SysUser::getUpdateTime,new Date());
            iSysUserService.update(null,lambdaUpdateWrapper);
            log.info("redis定时任务，购买会员卡到期取消会员资格结束");
        }
        // 删除失效的key
        stringRedisTemplate.delete(expiredKey);
        // 删除redis延时任务记录
        iTzRedisKeyService.deleteRedisKey(expiredKey);
    }
}
